/*
 * 地址选择
 */
'use strict';
import React, { Component } from 'react';
import {
    View,
    Text,
    StyleSheet,
    Image,
    ListView,
    RefreshControl,
    TouchableOpacity,
    Dimensions,
    Platform,
    Animated,
    TouchableHighlight,
    InteractionManager,
    AsyncStorage,
    Alert,
    ScrollView
} from 'react-native';


import Toast from 'antd-mobile/lib/toast';
import List from 'antd-mobile/lib/list';
import ActivityIndicator from 'antd-mobile/lib/activity-indicator';

import NavTitle from '../component/NavTitle';

import { connect } from 'react-redux';
import {changeAddress} from '../action/address';
import {getAll} from '../action/all';

const Item = List.Item;

import XFetch from '../XFetch';

import ServiceClassify from './ServiceClassify';

var _scrollView: ScrollView;

class Address extends Component {
  constructor(props) {
    super(props)

    this.state = {
        cityStatus: false,
        cityText: '',
        cityId: '',
        citys: [],
        animating:false,
        cityIds:[]
    }

    this.handleCityCancel = this.handleCityCancel.bind(this)
    this.handleCitySelect = this.handleCitySelect.bind(this)
    this.handleCityPress = this.handleCityPress.bind(this)
  }

  handleCityPress() {
    this.setState({
      cityStatus: true,
    })
  }

  handleCitySelect(cityObj) {
    this.props.changeAddress({
        name:cityObj.NAME,
        addressId:cityObj.ID
    });
    this.props.getAll(false);
    this.props.change(4);
  }
  handleCityCancel(){

  }

  componentDidMount(){
      this._changeAddress();
  }

  _changeAddress(ID=0,item = void 0){
      if(item && item.LAST){
          this.handleCitySelect(item);
          return;
      }
      this.setState({
          animating:true,
          cityIds:[...this.state.cityIds,ID]
      });
      Toast.loading('加载中',20);
      XFetch(`http://www.weiweigo.com/app/address.aspx?method=show&pid=${ID}`,{
          method:'GET'
      }).then(data=>{
          Toast.hide();
          _scrollView.scrollTo({ y: 0, animated: false})
          this.setState({
              citys:data,
              animating:false,
          })
      });
  }

  _getAddress(){
      navigator.geolocation.getCurrentPosition(
          (initialPosition) => {
              Toast.loading('数据加载中',30);
              fetch(`http://www.weiweigo.com/app/address.aspx?method=autoGetAddress&lat=${initialPosition.coords.latitude}&lon=${initialPosition.coords.longitude}`, {
                  method: 'GET'
              }).then(data=> {
                  Toast.hide();
                  data.json().then(data=> {
                      this.props.changeAddress({
                          name: data.name,
                          addressId: data.aid
                      });
                  })

              });
          },
          (error) => {
              Alert.alert('提示', '请先开启定位');
          },
          {enableHighAccuracy: false, timeout: 20000, maximumAge: 1000}
      );
  }

  _renderList(){
      return this.state.citys.map((obj,i)=>{
          return (
            <Item
              key={`list${i}${obj.ID}`}
              style={{backgroundColor:i%2===0?'#F3E9C5':'#FFF'}}
              arrow="horizontal"
              onClick={this._changeAddress.bind(this,obj.ID,obj)}
            >
                <View style={styles.itemStyle}>
                    <Text style={styles.keys}>{obj.LETTER}</Text>
                    <Text style={{fontSize:16}}>{obj.NAME}</Text>
                </View>
            </Item>
          )
      })
  }

    backTopLevel(){
        this.state.cityIds.pop();
        let id = this.state.cityIds.pop();

        this.setState({
            cityIds:[...this.state.cityIds]
        })
        this._changeAddress(id);
    }

  render() {
    return (
      <View style={styles.container}>
        <NavTitle
          title='定位地址'
          headColor = '#fbdc3a'
          leftImg = {this.state.cityIds.length !== 1?require('../imgs/left.png'):null}
          leftButton = {this.state.cityIds.length !== 1?true:false}
          leftText = {this.state.cityIds.length !== 1?"返回":''}
          leftHander = {()=>{
            this.backTopLevel();
          }}
        />
          {/*
          <View style={{padding:10,marginTop:5,backgroundColor:'#5f9bf8'}}>
              <Text style={{fontSize:16,color:'#FFF',fontWeight:'600'}}>
                  免费注册=同城微信推广平台朋友圈1万+微信好友浏览+全国各地3000加盟商*3000微信友=全国九千万微信好友同步浏览
              </Text>
          </View>*/}
          <ScrollView
              showsVerticalScrollIndicator={false}
              ref={(scrollView) => { _scrollView = scrollView; }}
          >
              <List style={{backgroundColor:'#FFF'}}>
                  <Item arrow="horizontal" onClick={this._getAddress.bind(this)}>
                      <View style={{flexDirection:"row",alignItems:'center'}}>
                          <Image source={require('../imgs/position.png')} style={{width:20,height:20}}/>
                          <Text style={{color:'#333',fontSize:14,marginLeft:10}}>一键定位</Text>
                      </View>
                  </Item>
              </List>
              <List style={styles.bgWhite}>
                  {this._renderList()}
              </List>
          </ScrollView>
      </View>
    )
  }

}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#F5F5F5',
        flex: 1,
    },
    itemStyle:{
       flexDirection:'row'
    },
    keys:{
      marginRight:10,
      fontSize:16
    }
});

const mapStateToProps = (state) => {
  return {
    address:state.address
  }
}

export default connect(
  mapStateToProps,{
    changeAddress,
    getAll
  }
)(Address)
